package com.woniu.tms.login.controller;

import com.woniu.tms.entity.Permission;
import com.woniu.tms.entity.Role;
import com.woniu.tms.entity.User;
import com.woniu.tms.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: peng
 */
@Controller
@RequestMapping("login")
public class LoginContorller {

    @Autowired
    LoginService loginService;

    @RequestMapping("loginDo")
    @ResponseBody
    public Map<String, Object> login(String loginName, String upwd, String code, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        User user = new User();
        user.setUphone(loginName);
        user.setSno(loginName);
        user.setUpwd(upwd);
        try {
            user = loginService.login(user);

            if (user != null) {
                String captcha = (String) request.getSession().getAttribute("captcha");
                if (code.equals(captcha)) {
                    List<Permission> trees = loginService.getTree(user);
                    Set<String> userPermissions = loginService.getUserPermissions(user);
                    List<Role> roleList = loginService.getRole(user.getUid());
                    Role role = roleList.get(0);
                    request.getSession().setAttribute("loginUser", user);
                    request.getSession().setAttribute("role", role);
                    request.getSession().setAttribute("trees", trees);
                    request.getSession().setAttribute("userPermissions", userPermissions);
                    map.put("result", true);
                } else {
                    map.put("result", false);
                    map.put("msg1", "验证码错误");
                }
            } else {
                map.put("result", false);
                map.put("msg2", "密码或是账号错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", false);
            map.put("msg3", e.toString());
        } finally {
            return map;
        }


    }

    @RequestMapping("exitDo")
    public String exitDo(HttpSession session) {
        session.invalidate();
        return "login";
    }

}
